package pers.karl.spring.boot.design.pattern.strategy;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class StrategyListContext {

    /**
     * 以spring对象的名称为key，未设置时对象名为类名转首字母小写
     */
    private Map<String,Strategy> strategyMap;

    @Autowired
    public void setStrategyList(List<Strategy> strategyList) {
        if(strategyList == null || strategyList.isEmpty()) {
            throw new IllegalArgumentException("no strategy found");
        }

        strategyMap = new HashMap<>(strategyList.size());

        for (Strategy strategy : strategyList) {
            strategyMap.put(strategy.support(), strategy);
        }
    }

    /**
     * 获取需要的策略
     * @param name
     * @return
     */
    public Strategy getStrategy(String name) {
        return strategyMap.get(name);
    }


}
